<?php
namespace app\api\controller\wdsxh;
use addons\wdsxh\library\Wxapp;
use app\admin\model\wdsxh\UserBelong;
use app\admin\model\wdsxh\Activity as Model;
use app\admin\model\wdsxh\Member;
use app\admin\model\wdsxh\Order;
use app\admin\model\wdsxh\ActivityApply;
use think\Exception;
use think\Db;
/**
 * 活动管理接口
 */
class Activity extends Base
{
    protected $noNeedLogin = ['lists','detail','payresult','applyUser'];
    protected $noNeedRight = ['*'];


    public function lists(){
        $page=$this->request->param('page',1);
        $limit=$this->request->param('limit',10);

        $type=$this->request->param('type',0);
        $cat=$this->request->param('cat',0);
        $state=$this->request->param('state',0);
        $keywords=$this->request->param('keywords',0);

        $user_id = $this->auth->id;

        $map = [
            'status' => ['>',0],
            'show' => 'all',
        ];
        if($user_id) {
            $member = model('app\admin\model\wdsxh\Member')->get(['uid' => $user_id,'status' => '1']);
            if($member) {
                $map['show'] = ['in',['all','member']];
            }
        }
        if(!empty($state)){
            $map['status']=$state;
        }
        if(!empty($type)){
            $map['type']=$type;
        }
        if(!empty($cat)){
            $map['unit_cat']=$cat;
        }
        if(!empty($keywords)){
            $map['title']=['like',"%{$keywords}%"];
        }
        $total=Model::where($map)
            ->order('weigh desc')
            ->count();
        $list=Model::where($map)
            ->order('weigh desc')
            ->page($page,$limit)
            ->select();
        $activityApplyModel = new ActivityApply();
        $apply_where['status'] = array('eq','1');
        if($list){
            foreach ($list as $row){
                $row->cat;
                $row['images'] = wdsxh_full_url($row['images'],true);
                $row['createtime']=date('Y-m-d H:i:s',$row['createtime']);
                $time=$row['time']?explode('-',$row['time']):'';
                $row->append(['start_time','end_time']);
                $row['start_time']=$time?date('Y-m-d H:i',strtotime(trim($time[0]))):'';
                $row['end_time']=$time?date('Y-m-d H:i',strtotime(trim($time[1]))):'';
                $row['apply_count'] = $activityApplyModel->where($apply_where)->where('activity_id',$row['id'])->count();
            }
        }
        $data=array(
            'total'=>$total,
            'list'=>$list
        );
        $this->success($data);
    }

    public function detail(){
        $id=$this->request->param('id');

        if(empty($id)){
            $this->error('请求参数错误');
        }

        $data=Model::get($id);
        if(!$data){
            $this->error('活动信息不存在');
        }

        if($data->show == 'member') {
            $user_id = $this->auth->id;
            if($user_id) {
                $member = model('app\admin\model\wdsxh\Member')->get(['uid' => $user_id,'status' => '1']);
                if(!$member) {
                    $this->error('该活动仅会员可参加',[],41001);
                }
            }else{
                $this->error('该活动仅会员可参加',[],41001);
            }
        }

        $data->cat;
        $data->images=wdsxh_full_url($data->images,true);
        $data->createtime=date('Y-m-d H:i:s',$data->createtime);
        $time=$data->time?explode('-',$data->time):'';
        $data->append(['start_time','end_time']);
        $data['start_time']=$time?date('Y-m-d H:i',strtotime(trim($time[0]))):'';
        $data['end_time']=$time?date('Y-m-d H:i',strtotime(trim($time[1]))):'';
        $data->append(['apply_num']);
        $data['apply_num']=ActivityApply::where('activity_id',$id)->where('status','1')->count();
        $this->success($data);
    }
    public function applyUser(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $page=$this->request->param('page',1);
        $limit=$this->request->param('limit',10);
        $id=$this->request->param('id');
        if(empty($id)){
            $this->error('请求参数错误');
        }
        $data=Model::get($id);
        if(!$data){
            $this->error('活动信息不存在');
        }
        $total=Db::name('wdsxh_activity_apply')
            ->alias('a')
            ->where('a.activity_id',$id)
            ->where('a.status','1')
            ->join('user b','a.user_id = b.id','LEFT')
            ->field("a.createtime,b.nickname,b.avatar")
            ->count();
        $list=Db::name('wdsxh_activity_apply')
            ->alias('a')
            ->where('a.activity_id',$id)
            ->where('a.status','1')
            ->join('user b','a.user_id = b.id','LEFT')
            ->field("a.createtime as applytime,b.nickname,b.avatar")
            ->page($page,$limit)
            ->select();
        foreach ($list as &$row){
            $row['avatar']=wdsxh_full_url($row['avatar']);
            $row['applytime']=date('Y-m-d H:i:s',$row['applytime']);
        }
        $data=array(
            'total'=>$total,
            'list'=>$list
        );
        $this->success($data);
    }
    /*
     * 活动报名
     */
    public function apply(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $id=$this->request->param('id');
        if(empty($id)){
            $this->error('请求参数错误');
        }
        $data=Model::get($id);
        $time=$data->time;
        if($time){
            $time=explode('-',$time);
            if(isset($time[1]) && time() > strtotime($time[1])){
                $this->error('活动报名截止时间为'.$time[1].'，无法继续报名');
            }
        }
        if(!$data){
            $this->error('活动信息不存在');
        }
        if($data['status'] == 0){
            $this->error('活动已关闭,暂停报名');
        }
        if($data['status'] == 2){
            $this->error('活动进行中,暂停报名');
        }
        if($data['status'] == 3){
            $this->error('活动已结束,暂停报名');
        }
        $data->cat;
        $data->images=wdsxh_full_url($data->images,true);
        $data->createtime=date('Y-m-d H:i:s',$data->createtime);
        $time=$data->time?explode('-',$data->time):'';
        $data->append(['start_time','end_time']);
        $data['start_time']=$time?date('Y-m-d H:i',strtotime(trim($time[0]))):'';
        $data['end_time']=$time?date('Y-m-d H:i',strtotime(trim($time[1]))):'';

        $money=$data['price'];
        $user_id=$this->auth->id;
        $member=Member::where('uid',$user_id)->find();

        if($member && $member['status'] == 1){
            $money=$data['vip_price'];
        }
        $data->hidden(['price','vip_price','content','weigh','unit_cat']);
        $data->append(['money']);
        $data['money']=$money;
        $this->success($data);
    }
    /*
     * 报名支付
     */
    public function applyPay(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $id=$this->request->param('id');
        if(empty($id)){
            $this->error('请求参数错误');
        }
        $data=Model::get($id);
        if(!$data){
            $this->error('活动信息不存在');
        }
        if($data['status'] == 0){
            $this->error('活动已关闭,暂停报名');
        }
        if($data['status'] == 2){
            $this->error('活动进行中,暂停报名');
        }
        if($data['status'] == 3){
            $this->error('活动已结束,暂停报名');
        }

        $applyNum=ActivityApply::where(array('activity_id'=>$data['id'],'status'=>'1'))->count();
        if($applyNum >= $data['population']){
            $this->error('活动报名人数已满');
        }

        $user=\app\admin\model\User::get($this->auth->id);

        if(!$user || $user['status'] != 'normal'){
            $this->error('用户信息不存在或已被拉黑');
        }

        $money=$data['price'];            //非会员报名价格
        $user_id=$this->auth->id;
        $member=Member::where('uid',$user_id)->find();
        if($member && $member['status'] == 1){        //会员报名价格
            $money=$data['vip_price'];
        }

        $apply=ActivityApply::where(array('user_id'=>$user_id,'activity_id'=>$data['id']))->find();
        if($apply && $apply['status'] == '1'){
            $this->error('你已报名过了，不能重复报名');
        }
        if($apply && $apply['status'] == '2'){
            $this->error('你的报名信息正在申请退款处理，暂时无法报名');
        }

        /**
         * 增加非会员报名填写信息
        */
        $name = $this->request->param('name');
        $mobile = $this->request->param('mobile');
        $chamber_of_commerce = $this->request->param('chamber_of_commerce');
        $chamber_of_commerce_position = $this->request->param('chamber_of_commerce_position');
        $company = $this->request->param('company');
        $company_position = $this->request->param('company_position');
        if(!$member) {
//            if(!$name || !$mobile || !$chamber_of_commerce || !$chamber_of_commerce_position || !$company || !$company_position)
            if(!$name || !$mobile)
            {
                $this->error('请填写基础信息');
            }
        }
        /**End**/

        if($apply){
            $apply['money']=$money;
            $apply['createtime']=time();
//            $apply['status']=floatval($money) == 0?'1':'0';
            $apply['status']='0';

            /**
             * 增加非会员报名填写信息
             */
            $apply['name'] = $name;
            $apply['mobile'] = $mobile;
            $apply['chamber_of_commerce'] = $chamber_of_commerce;
            $apply['chamber_of_commerce_position'] = $chamber_of_commerce_position;
            $apply['company'] = $company;
            $apply['company_position'] = $company_position;
            /**End**/

            $apply->save();
        }else{
            $applyData = array(
                'user_id' => $user_id,
                'activity_id' => $data['id'],
                'money' => $money,
//                'status'=>floatval($money) == 0?'1':'0',
                'status' => '0',
                'createtime' => time()
            );

            /**
             * 增加非会员报名填写信息
             */
            $applyData = array_merge($applyData,[
                'name' => $name,
                'mobile' => $mobile,
                'chamber_of_commerce' => $chamber_of_commerce,
                'chamber_of_commerce_position' => $chamber_of_commerce_position,
                'company' => $company,
                'company_position' => $company_position,
            ]);
            /**End**/

            $apply=ActivityApply::create($applyData);
        }
        if($apply){
            $map=array(
                'uid'=>$this->auth->id,
                'items_id'=>$apply['id'],
                'type'=>1
            );
            $order=Order::where($map)->find();
            if($order){
                $order['order_sn']=wdsxh_create_order();
                $order['money']=$money;
                $order['status']=floatval($money) == 0?'2':'1';
                $order['createtime']=time();
                $order->save();
            }else{
                $orderData=array(
                    'uid'=>$this->auth->id,
                    'items_id'=>$apply['id'],
                    'type'=>1,
                    'order_sn'=>wdsxh_create_order(),
                    'money'=>$money,
                    'status'=>$money == 0?'2':'1',
                    'createtime'=>time()
                );
                $order=Order::create($orderData);
            }
            if($order->money == 0 && $order->status == 2){
                //活动报名成功通知
//                try{
//                    $activity=Model::get($apply->activity_id);
//                    $time=explode('-',$activity->time);
//                    $startTime=strtotime(trim($time[0]));
//                    $conf=$this->configObj;
//                    $data=[
//                        'thing1'=>[
//                            'value'=>$activity['title'],
//                        ],
//                        'amount3'=>[
//                            'value'=>$apply['money'],
//                        ],
//                        'thing6'=>[
//                            'value'=>$activity['address'],
//                        ],
//                        'date7'=>[
//                            'value'=>date('Y年m月d日 H:i',$startTime),
//                        ],
//                        'phone_number8'=>[
//                            'value'=>$activity['tel'],
//                        ]
//                    ];
//                    Wxapp::subscribeMessage($conf['activity_apply'],trim(wdsxh_get_openid($user_id)),'/pages/Functions/index',$data);
//                }catch (\think\Exception $e){
//
//                }
                $this->success('报名成功');
            }else{
                if($data['pay_type']== 1){          //在线支付
                    try{
                        $openid = (new UserBelong())->where('user_id',$user['id'])->value('openid');
                        $conf=Wxapp::unify('商会活动报名',$order->order_sn,$order->money,$openid,request()->domain().'/api/wdsxh/activity/payresult');
                    }catch (Exception $e){
                        $this->error($e->getMessage());
                    }
                    $this->success('success',$conf,2);
                }else{                               //线下支付
                    $this->success('报名成功，请到线下进行支付报名费用',null,3);
                }
            }
        }else{
            $this->error('创建订单失败');
        }
    }
    /*
     * 活动报名支付处理
     */
    public function payResult(){
        $pay=Wxapp::getPay();
        $response = $pay->handlePaidNotify(function($message, $fail){
            $order = Order::where('order_sn',$message['out_trade_no'])->find();
            if (!$order || $order['status'] == '2') {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    $order['paytime'] = time();
                    $order['status'] = '2';
                    //处理活动报名
                    $apply=ActivityApply::where('id',$order->items_id)->find();
                    $apply['status']='1';
                    $apply->save();

                    //活动报名成功通知
                    try{
                        $activity=Model::get($apply['activity_id']);
                        $time=explode('-',$activity['time']);
                        $startTime=strtotime(trim($time[0]));
                        $conf=$this->configObj;
                        $data=[
                            'thing1'=>[
                                'value'=>mb_substr($activity['title'],0,20),
                            ],
                            'amount3'=>[
                                'value'=>$apply['money'],
                            ],
                            'thing6'=>[
                                'value'=>mb_substr($activity['address'],0,20),
                            ],
                            'date7'=>[
                                'value'=>date('Y年m月d日 H:i',$startTime),
                            ],
                            'phone_number8'=>[
                                'value'=>$activity['tel'],
                            ]
                        ];
                        Wxapp::subscribeMessage($conf['activity_apply'],trim(wdsxh_get_openid($apply->user_id)),'/pages/Functions/index',$data);
                    }catch (\think\Exception $e){

                    }

                } elseif ($message['result_code'] === 'FAIL') {
                    $order->status = '3';
                }
            } else {
                return $fail('FAIL');
            }
            $order->save();
            return true;
        });

        $response->send();
    }
    /*
     * 获取报名订单
     */
    public function applyOrder(){
        $user_id=$this->auth->id;
        $page=$this->request->param('page',1);
        $limit=$this->request->param('limit',10);
        $payState=$this->request->param('pay_state',0);
        $activityState=$this->request->param('activity_state',0);
        $map=array(
            'ActivityApply.user_id'=>$user_id
        );
//        if(!empty($payState)){
            if($payState == 1){
                $map['ActivityApply.status']='1';
            }elseif ($payState == 3){
                $map['ActivityApply.status']='3';
            }elseif ($payState == 2){
                $map['ActivityApply.status']='2';
            }elseif ($payState == 4){
                $map['ActivityApply.status']='4';
            }elseif ($payState == 0){
                $map['ActivityApply.status']='0';
            }
//        }
        $activityMap=array(
            'status'=>array('>','0')
        );
        if(!empty($activityState)){
            $activityMap['status']=$activityState;
        }
        $total=ActivityApply::hasWhere('activity',$activityMap)->where($map)->count();
        $list=ActivityApply::hasWhere('activity',$activityMap)->where($map)->order('createtime desc')->page($page,$limit)->select();
        if($list){
            foreach ($list as $row){
                $row->activity;
                if($row->activity){
                    $row->createtime=date('Y-m-d H:i:s',$row->createtime);
                    $row->activity->cat;
                    $row->activity->images=wdsxh_full_url($row->activity->images,1);
                    $time=$row->activity->time?explode('-',$row->activity->time):'';
                    $row->activity->append(['start_time','end_time']);
                    $row->activity->start_time=$time?date('Y-m-d H:i',strtotime(trim($time[0]))):'';
                    $row->activity->end_time=$time?date('Y-m-d H:i',strtotime(trim($time[1]))):'';
                    $row->hidden(['user_id','activity_id']);
                }
            }
        }
        $data=array(
            'total'=>$total,
            'list'=>$list
        );
        $this->success($data);
    }

    public function applyList(){
        $id=$this->request->param('id');
        if(empty($id)){
            $this->error('请求参数错误');
        }
        $map=array(
            'activity_apply.activity_id'=>$id,
            'activity_apply.status'=>'1',
        );
        $list=ActivityApply::with(['user'])->where($map)->order('createtime desc')->select();
        $tmp=array();
        if($list){
            $list=collection($list)->toArray();
            foreach ($list as $row){
                $item=array(
                    'id'=>$row['id'],
                    'activity_id'=>$row['activity_id'],
                    'user_id'=>$row['user']['id'],
                    'avatar'=>wdsxh_full_url($row['user']['avatar']),
                    'nickname'=>$row['user']['nickname']
                );
                $tmp[]=$item;
            }
        }
        $this->success($tmp);
    }

    public function stats(){
        $map=array(
            'ActivityApply.user_id'=>$this->auth->id
        );
        $dsh=ActivityApply::hasWhere('activity',array('status'=>array('in',array('1'))))->where($map)->where('ActivityApply.status','=','0')->count();
        $bmz=ActivityApply::hasWhere('activity',array('status'=>array('in',array('1'))))->where($map)->where('ActivityApply.status','=','1')->count();
        $jxz=ActivityApply::hasWhere('activity',array('status'=>array('in',array('2'))))->where($map)->where('ActivityApply.status','=','1')->count();
        $yjs=ActivityApply::hasWhere('activity',array('status'=>array('in',array('3'))))->where($map)->where('ActivityApply.status','=','1')->count();
        $ytk=ActivityApply::hasWhere('activity',array('status'=>array('in',array('0','1','2','3'))))->where($map)->where('ActivityApply.status','=','3')->count();
        $data=array(
            'dsh'=>$dsh,
            'bmz'=>$bmz,
            'jxz'=>$jxz,
            'yjs'=>$yjs,
            'ytk'=>$ytk,
        );
        $this->success($data);
    }

    /*
     * 取消/退款
     */
    public function cancel(){
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $applyId=$this->request->param('apply_id',0);
        $activityId=$this->request->param('activity_id',0);

        if(empty($applyId)){
            $this->error('apply_id参数信息错误');
        }
        if(empty($activityId)){
            $this->error('activity_id参数信息错误');
        }
        $apply=ActivityApply::where('id',$applyId)->where('user_id',$this->auth->id)->where('activity_id',$activityId)->find();

        if(!$apply){
            $this->error('活动报名信息不存在');
        }
        $activity=Model::get($activityId);
        if(empty($activity)){
            $this->error('活动信息不存在');
        }
        if($activity['status'] == '1'){
            if($apply['status'] == '0'){
                $map=array(
                    'uid'=>$this->auth->id,
                    'items_id'=>$apply->id,
                    'type'=>1,
                );
                Order::where($map)->update(array('status'=>'0'));
                $apply->delete();
                $this->success('取消成功');
            }elseif ($apply['status'] == '1'){//已支付
                if($apply['money'] == 0.00) {
                    $apply['status']='3';//已退款
                    $apply->save();
                    $this->success('已取消');
                }
                if($activity['refund'] == 0 && $apply['money'] != 0.00){
                    $this->error('该活动不允许退款操作');
                }
                $activeMode = (new \app\admin\model\wdsxh\Activity())->where('id',$activityId)->find();
                if ($activeMode['pay_type'] == 1 && $apply['money'] != 0.00){//在线支付并退款
                    if($this->refund($activityId,$apply['id'],$this->auth->id)){//
                        $apply['status'] = '2';
                        $apply->save();
                        $this->error('退款已申请，待管理员审核');
                    }else{
                        $this->error('退款发生错误');
                    }
                }elseif ($activeMode['pay_type'] == 2){//线下付款
                    $apply['status']='2';
                    $apply->save();
                    $this->error('请联系发布人退款');
                }
            }elseif ($apply['status'] == '2'){
                $this->error('已在退款中');
            }elseif ($apply['status'] == '3'){
                $this->error('已退款');
            }elseif ($apply['status'] == '4'){
                $this->error('已完成');
            }
        }elseif ($activity['status'] == '0'){
            $this->error('活动已关闭，请联系主办方');
        }elseif ($activity['status'] == '2'){
            $this->error('活动已在进行中，无法退款或取消操作');
        }elseif ($activity['status'] == '3'){
            $this->error('活动已结束，无法退款或取消操作');
        }else{
            $this->error('未知的活动状态');
        }
    }
    /*
     *  退款处理
     */
    private function refund($activeId,$applyId,$uid){
        $active=Model::get($activeId);
        if(!$active){
            $this->error('活动信息不存在');
        }
        if($active['status'] != '1'){
            $this->error('活动状态信息错误');
        }



        $member=Member::where('uid',$uid)->field('id,name,mobile')->find();
        if(!$member){
            $this->error('会员信息不存在');
        }
        $activeMode = (new \app\admin\model\wdsxh\Activity())->where('id',$activeId)->field('pay_type')->find();
        if ($activeMode['pay_type'] == 1){
            $order=Order::where('uid',$uid)
                ->where('items_id',$applyId)
                ->where('type',1)
                ->where('status','2')
                ->find();
        }elseif ($activeMode['pay_type'] == 2){
            $order = (new Order())
                ->alias('order')
                ->join('wdsxh_activity_apply apply','apply.id = order.items_id')
                ->where('order.items_id',$applyId)
                ->where('order.type',1)
                ->where('apply.status','1')
                ->find();
        }

        if(!$order){
            $this->error('订单支付信息不存在');
        }
        if($order['money'] == 0){
            return true;
        }
        $refundData=array(
            'user_id'=>$uid,
            'member_id'=>$member?$member['id']:0,
            'activity_id'=>$activeId,
            'apply_id'=>$applyId,
            'money'=>$order['money'],
            'status'=>'0',
            'createtime'=>time()
        );
        $res=\app\admin\model\wdsxh\ActivityRefund::create($refundData);
        if($res) {
            return true;
        } else {
            $this->error('活动退款失败');
        }
    }
}